<?php
namespace Template;

use Twig_SimpleFilter;
use Utils\Helper;

final class Twig {
    /**
     * @var \Twig_Environment
     */
	private $twig;
	private $data = array();

    const DATA_KEY_FILTERS = 'twig_filters';
    const DATA_KEY_FNS = 'twig_fns';

    public function set($key, $value) {
		$this->data[$key] = $value;
	}

    /**
     * @param $template
     * @param bool $cache
     *
     * @return string
     */
    public function render($template, $cache = false) {
		// specify where to look for templates
		$loader = new \Twig_Loader_Filesystem(DIR_TEMPLATE);

		// initialize Twig environment
		$config = array('autoescape' => false);

		if ($cache) {
			$config['cache'] = DIR_CACHE;
		}

		$this->twig = new \Twig_Environment($loader, $config);

        $this->addTwigFilters();
        $this->addTwigFns();

		try {
		    $this->data['helper'] = Helper::getSingleton();
			// load template
			$twig_template = $this->twig->loadTemplate($template . '.twig');

			return $twig_template->render($this->data);
		} catch (\Exception $e) {
			trigger_error('Error: Could not load template ' . $template . '!');
			exit();
		}
	}

	private function globalTwigFilters()
    {
        // twig usage: {{ some_var | dd }} or {{ some_var | dd(param2, param3, ...) }}
        return [
            new \Twig_SimpleFilter('dd', 'dd')
        ];
    }

	private function globalTwigFns()
    {
        // twig usage: {{ dd(some_var) }}
        return [
            new \Twig_SimpleFunction('dd', 'dd')
        ];
    }

    /**
     * 从 data 增加自定义的 filter 函数
     */
    private function addTwigFilters()
    {
        $filters = $this->globalTwigFilters();

        if (isset($this->data[self::DATA_KEY_FILTERS])
            && is_array($this->data[self::DATA_KEY_FILTERS])
        ) {
            $filters = array_merge($filters, $this->data[self::DATA_KEY_FILTERS]);
        }

        foreach ($filters as $filter) {
            $this->twig->addFilter($filter);
        }
    }

    /**
     * 从 data 增加自定义的 function 函数
     */
    private function addTwigFns()
    {
        $fns = $this->globalTwigFns();

        if (isset($this->data[self::DATA_KEY_FNS])
            && is_array($this->data[self::DATA_KEY_FNS])
        ) {
            $fns = array_merge($fns, $this->data[self::DATA_KEY_FNS]);
        }

        foreach ($fns as $fn) {
            $this->twig->addFunction($fn);
        }
    }
}
